var token;
var ser_key_flag=0;
var multi_ser_key_flag=0;
var checkrp_flag=0;
var con_mcn_list=[];
var is_vip=0;
var lasttime = null;
var popup_active_tab =null;
var self_list_mcn = null;

var http_prefix = "http://localhost:5002";

async function post_check_mcn(){
    var obj_mcn = await get_self_list_mcn();

    if(obj_mcn==null){
        return {
            code:1,
            msg:'获取信息失败，请登陆知乎'
        };
    }

    if(obj_mcn.jd_mcn.length!=0 || obj_mcn.tb_mcn.length!=0){
        var post_data = {
            jd_mcn:obj_mcn.jd_mcn,
            tb_mcn:obj_mcn.tb_mcn
        }
        var res = await checkmcn(post_data);

        if(res.code!=0){
            return {
                code:1,
                msg:'检查好物信息失败'
            };
        }

        var jd_list = res.data.jd_list;
        var tb_list = res.data.tb_list;

        console.log(res);

        for(var i=0;i<obj_mcn.answer_list_mcn.length;i++){
            var tmp_answer = obj_mcn.answer_list_mcn[i];
            for(k=0;k<tmp_answer.mcn_list.length;k++){
                var tmp = tmp_answer.mcn_list[k];
                if(tmp.source=='京东'){
                    if(jd_list.indexOf(Number(tmp.skuid))!=-1){
                        tmp.isvaild=true;
                        continue;
                    }
                }else if(tmp.source=='淘宝'){
                    if(tb_list.indexOf(Number(tmp.skuid))!=-1){
                        tmp.isvaild=true;
                        continue;
                    }
                }
            }
        }
        
        for(var i=0;i<obj_mcn.article_list_mcn.length;i++){
            var tmp_answer = obj_mcn.article_list_mcn[i];
            for(k=0;k<tmp_answer.mcn_list.length;k++){
                var tmp = tmp_answer.mcn_list[k];
                if(tmp.source=='京东'){
                    if(jd_list.indexOf(Number(tmp.skuid))!=-1){
                        tmp.isvaild=true;
                        continue;
                    }
                }else if(tmp.source=='淘宝'){
                    if(tb_list.indexOf(Number(tmp.skuid))!=-1){
                        tmp.isvaild=true;
                        continue;
                    }
                }
            }
        }

        var answer_list = [];
        for(var i=0;i<obj_mcn.answer_list_mcn.length;i++){
            var tmp_answer = obj_mcn.answer_list_mcn[i];
            var mcn_tmp_list = [];
            for(k=0;k<tmp_answer.mcn_list.length;k++){
                var tmp = tmp_answer.mcn_list[k];
                if(tmp.isvaild==null){
                    mcn_tmp_list.push(tmp);
                }
            }
            if(mcn_tmp_list.length>0){
                tmp_answer.mcn_list = mcn_tmp_list;
                answer_list.push(tmp_answer);
            }
        }

        var article_list = [];
        for(var i=0;i<obj_mcn.article_list_mcn.length;i++){
            var tmp_answer = obj_mcn.article_list_mcn[i];
            var mcn_tmp_list = [];
            for(k=0;k<tmp_answer.mcn_list.length;k++){
                var tmp = tmp_answer.mcn_list[k];
                if(tmp.isvaild==null){
                    mcn_tmp_list.push(tmp);
                }
            }
            if(mcn_tmp_list.length>0){
                tmp_answer.mcn_list = mcn_tmp_list;
                article_list.push(tmp_answer);
            }
        }

        if(answer_list.length==0 && article_list.length==0){
            return {
                code:1,
                msg:'已检查完成，没有发现过期链接'
            };
        }

        obj_mcn.answer_list_mcn = answer_list;
        obj_mcn.article_list_mcn = article_list;
        obj_mcn.code = 0;
        console.log(obj_mcn);

        this.self_list_mcn = obj_mcn;
        return obj_mcn;

    }else{
        return {
            code:1,
            msg:'帐号没有好物信息'
        };
    }
}

async function get_self_list_mcn(){
    var self = await get_self();
    console.log(self);
    if(self.id==null){
        return null;
    }
    var self_id = self.id;
    var self_token = self.url_token;
    var nikename = self.name;

    var answer_list = [];
    var article_list = [];
    var answer_list_mcn = [];
    var article_list_mcn = [];
    var jd_mcn = [];
    var tb_mcn = [];

    await get_anwser_list(answer_list,self_id,null);
    await get_article_list(article_list,self_token,null,1);

    console.log(answer_list);
    console.log(article_list);

    if(answer_list.length>0){
        for(var i=0;i<answer_list.length;i++){
            var tmp = answer_list[i];
            var tmp_id = tmp.id;
            var type = 0;
            var mcn_res = await get_mcn(tmp_id,type);
            if(mcn_res.totals!=0){
                var mcn_list = clean_mcn_info_list(mcn_res.data);
                tmp.mcn_list = mcn_list;
                tmp.mcn_num = mcn_list.length;
                answer_list_mcn.push(tmp);
                for(k=0;k<mcn_list.length;k++){
                    var mcntmp = mcn_list[k];
                    if(mcntmp.source=='京东'){
                        jd_mcn.push(mcntmp.skuid);
                    }else if(mcntmp.source=='淘宝'){
                        tb_mcn.push(mcntmp.skuid);
                    }
                }
            }
            await sleep(100);
        }
    }

    if(article_list.length>0){
        for(var i=0;i<article_list.length;i++){
            var tmp = article_list[i];
            var tmp_id = tmp.id;
            var type = 1;
            // tmp_id = "216243295";
            var mcn_res = await get_mcn(tmp_id,type);
            console.log(mcn_res);
            if(mcn_res.totals!=0){
                var mcn_list = clean_mcn_info_list(mcn_res.data);
                tmp.mcn_list = mcn_list;
                tmp.mcn_num = mcn_list.length;
                article_list_mcn.push(tmp);
                for(k=0;k<mcn_list.length;k++){
                    var mcntmp = mcn_list[k];
                    if(mcntmp.source=='京东'){
                        jd_mcn.push(mcntmp.skuid);
                    }else if(mcntmp.source=='淘宝'){
                        tb_mcn.push(mcntmp.skuid);
                    }
                }
            }
            await sleep(100);
        }
    }
    
    jd_mcn = uniq(jd_mcn);
    tb_mcn = uniq(tb_mcn);

    var obj = {
        answer_list_mcn:answer_list_mcn,
        article_list_mcn:article_list_mcn,
        nikename:nikename,
        jd_mcn:jd_mcn,
        tb_mcn:tb_mcn
    }
    console.log(obj);
    return obj;
}

async function get_self(){
    var url = "https://api.zhihu.com/people/self";
    var res = await geturl(url);
    return res;
}

function clean_mcn_info_list(list){
    var tmplist = [];
    for(var i=0;i<list.length;i++){
        var tmp = list[i];
        var obj = {
            id:tmp.id,
            url:tmp.url,
            title:tmp.title,
            img_url:tmp.img_url,
            source:tmp.source,
            skuid:tmp.skuid,
            price_text:tmp.price_text
        }
        tmplist.push(obj);
    }
    return tmplist;
}

async function get_mcn(id,type){
    var url = "https://www.zhihu.com/api/v4/mcn/goods/incontent?content_token="+id+"&content_type="+type+"&scenes=1";
    var res = await geturl(url);
    return res;
}

async function get_anwser_list(answer_list,id,url){
    if(id!=null){
        url = "https://api.zhihu.com/members/"+id+"/answers?limit=20&order_by=created&offset=0";
    }else{
        url = url.replace("http","https");
    }
    var res = await geturl(url);
    console.log(res);
    if(res.paging==null){
        return;
    }

    if(res.data.length>0){
        var concat_list = [];
        for(var i=0;i<res.data.length;i++){
            var tmp = res.data[i];
            var obj = {
                id:tmp.id,
                title:tmp.question.title,
                question_id:tmp.question.id
            }
            concat_list.push(obj);
        }
        // console.log(concat_list);
        // console.log(answer_list);
        answer_list.push.apply(answer_list,concat_list);
        // console.log(answer_list);
        if(!res.paging.is_end){
            await sleep(100);
            await get_anwser_list(answer_list,null,res.paging.next)
        }
    }
}

async function get_article_list(article_list,token,url,i){

    if(token!=null){
        var s1 = formatDateTimeyyyyMMdd(new Date());
        url = "https://www.zhihu.com/api/v4/creator/content_statistics/articles?begin_date=2009-08-15&end_date="+s1+"&order_sort=descend&page_no="+i;
        // url = "https://www.zhihu.com/api/v4/members/"+token+"/articles?include=data%5B*%5D.comment_count%2Csuggest_edit%2Cis_normal%2Cthumbnail_extra_info%2Cthumbnail%2Ccan_comment%2Ccomment_permission%2Cadmin_closed_comment%2Cvoteup_count%2Ccreated%2Cupdated%2Cupvoted_followees%2Cvoting%2Creview_info%2Cis_labeled%2Clabel_info%3Bdata%5B*%5D.author.badge%5B%3F(type%3Dbest_answerer)%5D.topics&offset=0&limit=20&sort_by=created";
    }else{
        url = url.replace("http","https");
    }
    var res = await geturl(url);
    console.log(res);
    

    if(res.data==null){
        return;
    }

    if(res.data.length>0){
        var concat_list = [];
        for(var i=0;i<res.data.length;i++){
            var tmp = res.data[i];
            var obj = {
                id:tmp.url_token,
                title:tmp.title
            }
            concat_list.push(obj);
        }
        // console.log(concat_list);
        article_list.push.apply(article_list,concat_list);
        await get_article_list(article_list,token,null,i+1);
    }
    
}

function getmcn_list(obj,callback){
    var qry = {
        pageSize:obj.pageSize,
        pageNo:obj.pageNo,
        orderby:obj.orderby,
        ordertype:obj.ordertype,
        token: this.token,
    };
    var url;
    if(obj.mode=="mcn"){
        url = http_prefix+"/api/goods/getlist";
    }else if(obj.mode=="article"){
        url = http_prefix+"/api/content/getlist";
    }
    // console.log(obj);
    $.ajax({
        url: url,
        cache: false,
        type: "POST",
        data: JSON.stringify(qry),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        if(obj.mode = "article"){
            con_mcn_list = res.data;
        }
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

async function checkmcn(obj){
    return new Promise(function(resolve, reject) {
        obj.token = this.token;
        $.ajax({
            url: http_prefix+"/api/content/check_self_mcn",
            cache: false,
            type: "POST",
            data: JSON.stringify(obj),
            contentType: "application/json",
            dataType: "json"
        }).done(function (res) {
            resolve(res);
        }).fail(function (jqXHR, textStatus) {
            // console.log(textStatus);
            reject();
        });
    });
}

async function checktoken(callback) {
    this.token = await getStoreTxt("token");
    var obj = {
        token: this.token,
    };
    // console.log(obj);
    $.ajax({
        url: http_prefix+"/api/user/checktoken",
        cache: false,
        type: "POST",
        data: JSON.stringify(obj),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        if(res.data.is_vip!=null){
            is_vip=1;
            lasttime = res.data.lasttime;
        }else{
            is_vip=0;
            lasttime = res.data.lasttime;
        }
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        console.log(textStatus);
    });
}


function updatepass(mail,pwd,code,callback){
    var obj = {
        mail: mail,
        pwd:pwd,
        seccode:code
    };
    $.ajax({
        url: http_prefix+"/api/login/updatepassword",
        cache: false,
        type: "POST",
        data: JSON.stringify(obj),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function mailseccode(mail,callback){
    var obj = {
        mail: mail,
    };
    $.ajax({
        url: http_prefix+"/api/login/forgetpassword",
        cache: false,
        type: "POST",
        data: JSON.stringify(obj),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function register(mail, pwd, callback) {
    var obj = {
        mail: mail,
        pwd: pwd
    };
    $.ajax({
        url: http_prefix+"/api/login/register",
        cache: false,
        type: "POST",
        data: JSON.stringify(obj),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function login(mail, pwd, callback) {
    var obj = {
        mail: mail,
        pwd: pwd
    };
    $.ajax({
        url: http_prefix+"/api/login",
        cache: false,
        type: "POST",
        data: JSON.stringify(obj),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function getStore(key,callback){
    chrome.storage.local.get(key, callback);
}

async function getStoreTxt(key){
    var restr = await read(key);
    // console.log(restr[key]);
    return restr[key];
}

async function read(key) {
    return new Promise((resolve, reject) => {
        if (key != null) {
            chrome.storage.local.get(key, function (obj) {
                resolve(obj);
            });
        } else {
            reject(null);
        }
    });
}

function uniq(array){
    var temp = []; //一个新的临时数组
    for(var i = 0; i < array.length; i++){
        if(temp.indexOf(array[i]) == -1){
            temp.push(array[i]);
        }
    }
    return temp;
}

async function flashbgtoken(){
    this.token =await getStoreTxt("token");
}


/**
 * 日期格式化
 * @param inputTime
 * @returns {string}
 */
function formatDateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}

function formatDateTimeyyyyMMdd(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
}

init();

async function init(){
    console.log("bg*********init");
    await flashbgtoken();
}

async function sendurl(request,sendResponse){
    request.token= this.token;
    
    var url;
    if(request.mode=="mcn_add" || request.mode=="mcn_delete"){
        url = http_prefix+"/api/goods/save";
    }else if(request.mode=="mcn_id_list"){
        url = http_prefix+"/api/goods/getall_mcnid_byuser";
    }else if(request.mode=="content_add" || request.mode=="content_delete"){
        url = http_prefix+"/api/content/save";
    }else if(request.mode=="content_id_list"){
        url = http_prefix+"/api/content/getall_id_byuser";
    }else if(request.mode=="copy_cp"){
        var obj = {
            copy:1,
            text:request.text
        }
        chrome.storage.local.set({'checkrp': obj}, function() {});
        return true;
    }else if(request.mode=="follow_id"){
        let res =  await read('follow_q');
        console.log(res);
        sendResponse(res);
        return true;
    }else{
        return true;
    }
    $.ajax({
        url: url,
        cache: false,
        type: "POST",
        data: JSON.stringify(request),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        // console.log(res);
        sendResponse(res);
    }).fail(function (jqXHR, textStatus) {
        sendResponse(-1);
    });
}

chrome.extension.onMessage.addListener(
    function (request, sender, sendResponse) {
        // console.log("*******evenPage.js***chrome.extension.onMessage.addListener");
        // console.log(request);

        // console.log(sender);
        sendurl(request,sendResponse);

        return true;
    }
);

async function geturl(url){
    return new Promise(function(resolve, reject) {
        $.ajax({
            url: url,
            cache: false,
            type: "GET",
            contentType: "application/json",
        }).done(function (res) {
            // console.log(res);
            resolve(res);
        }).fail(function (jqXHR, textStatus) {
            // console.log(textStatus);
            resolve(null);
        });
    });
}

async function serkey(key){
    var res = {};
    res.key = key;
    var answer_num_sum = 0;
    var mcn_num_sum = 0;
    var visit_sum = 0;
    var follower_sum = 0;
    var answer_yes = 0;
    var answer_id_length = 0;
    
    var question_id_list = [];
    var url = "https://api.zhihu.com/search_v3?limit=20&offset=0&t=general&q="+key;
    await key_ser(question_id_list,url);
    // console.log(question_id_list);
    res.question_num = question_id_list.length;
    res.data = [];
    for(var i=0;i<question_id_list.length;i++){
        var answer_id_list = [];
        var question_url = "https://api.zhihu.com/questions/"+question_id_list[i]+"/answers?offset=0&limit=20&sort_by=default";
        await answer_list(answer_id_list,question_url);
        await sleep(200);
        // console.log(answer_id_list);
        var question = {};
        
        question.data=[];
        var question_detail_url = "https://api.zhihu.com/questions/" + question_id_list[i] + "?include=visit_count%2Canswer_count%2Cfollower_count";
        var detail = await get_detail(question_detail_url);
        if(detail==null || detail.id==null){
            continue;
        }
        question.answer_num = answer_id_list.length;
        answer_id_length = answer_id_length + answer_id_list.length;
        answer_num_sum = answer_num_sum + detail.answer_count;
        question.visit_count = detail.visit_count;
        visit_sum = visit_sum + detail.visit_count;
        question.answer_count = detail.answer_count;
        question.follower_count = detail.follower_count;
        follower_sum = follower_sum + detail.follower_count;
        question.title = detail.title;
        question.url = detail.url;
        question.id= detail.id;

        var answer_mcn_num = 0;
        var answer_yes_num = 0;
        for(var k=0;k<answer_id_list.length;k++){
            var answer_detail_url = "https://api.zhihu.com/answers/"+answer_id_list[k]+"?include=voteup_count";
            var answer_detail = await get_detail(answer_detail_url);
            await sleep(100);
            if(answer_detail ==null  || answer_detail.id==null){
                continue;
            }
            var mcn_num_url = "https://www.zhihu.com/api/v4/mcn/goods/incontent?content_token="+answer_id_list[k]+"&content_type=0&scenes=1";
            var mcn_num = await get_mcn_num(mcn_num_url);
            await sleep(100);
            // console.log(mcn_num);
            mcn_num_sum = mcn_num_sum + mcn_num;
            answer_yes = answer_yes + answer_detail.voteup_count;
            answer_mcn_num = answer_mcn_num + mcn_num;
            answer_yes_num = answer_yes_num + answer_detail.voteup_count;
            var answer = {
                id:answer_id_list[k],
                mcn_num:mcn_num,
                yes:answer_detail.voteup_count
            }
            question.data.push(answer);
        }
        question.mcn_num = answer_mcn_num;
        question.yes_num = answer_yes_num;

        var q_pj_yes = question.yes_num==0?0.01:question.yes_num/question.answer_num;
        var q_pj_mcn = question.mcn_num==0?0.01:question.mcn_num/question.answer_num;
        var pingfen = Math.log(question.visit_count/question.answer_count/5000)*100+Math.log(1000/q_pj_yes)*50+Math.log(1/q_pj_mcn)*100;
        question.pingfen = pingfen;
        
        res.data.push(question);
    }
    res.answer_num_sum = answer_num_sum;
    res.mcn_num_sum = mcn_num_sum;
    res.answer_yes = answer_yes;
    res.follower_sum = follower_sum;
    res.visit_sum = visit_sum;
    res.answer_id_length = answer_id_length;
    console.log(res);

    var question_list = res.data;

    question_list.sort(compare("pingfen")); 

    var baiduurl = "https://www.baidu.com/s?wd="+key+"&pn=0&rn=40&si=zhihu.com&ct=2097152&tn=json";

    var baidures = await geturl(baiduurl);

    if(baidures==null || baidures.feed==null || baidures.feed.entry==null){
        return res;
    }

    var baidulist = baidures.feed.entry;
    for(var i=0;i<baidulist.length;i++){
        var btmp = baidulist[i];

        var url = btmp.url;
        var reg_str = /www\.zhihu\.com\/question\/(\d+)/;
        if(!reg_str.test(url)){
            continue;
        }

        var mat = url.match(reg_str);

        if(mat.length!=2){
            continue;
        }

        var qid = mat[1];
        if(question_id_list.indexOf(qid)==-1){
            continue;
        }

        for(var k=0;k<question_list.length;k++){
            var tmp = question_list[k];
            if(tmp.id!=qid){
                continue;
            }

            tmp.baidu = true;
        }
    }

    return res;
}

async function ser_key(key,callback){
    await chrome.storage.local.remove('ser_key', function() {});
    ser_key_flag = 1;
    multi_ser_key_flag = 1;
    
    var res = await serkey(key);
    var pj_yes = res.answer_yes==0?0.01:res.answer_yes/res.answer_id_length;
    var pj_mcn = res.mcn_num_sum==0?0.01:res.mcn_num_sum/res.answer_id_length;
    var pf = Math.log(res.visit_sum/res.answer_num_sum/5000)*100+Math.log(1000/pj_yes)*50+Math.log(1/pj_mcn)*100;
    res.pf = pf;
    chrome.storage.local.set({'ser_key': res}, function() {});
    ser_send_history(res);
    ser_key_flag = 0;
    multi_ser_key_flag = 0;
    callback(res);
}

async function multi_ser_key(key_list,callback){
    multi_ser_key_flag = 1;
    ser_key_flag = 1;
    
    var ser_key_list = [];
    for(var i=0;i<key_list.length;i++){
        var key = key_list[i];
        var res = await serkey(key);

        var pj_yes = res.answer_yes==0?0.01:res.answer_yes/res.answer_id_length;
        var pj_mcn = res.mcn_num_sum==0?0.01:res.mcn_num_sum/res.answer_id_length;
        var pf = Math.log(res.visit_sum/res.answer_num_sum/5000)*100+Math.log(1000/pj_yes)*50+Math.log(1/pj_mcn)*100;
        res.pf = pf;
        ser_key_list.push(res);
        ser_send_history(res);
        await sleep(1000*20);
    }
    multi_ser_key_flag = 0;
    ser_key_flag = 0;
    callback(ser_key_list);
}

function ser_send_history(res,callback) {
    var obj = {
        obj: res,
        key: res.key,
        token:this.token
    };
    $.ajax({
        url: http_prefix+"/api/history/save",
        cache: false,
        type: "POST",
        data: JSON.stringify(obj),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        if(callback!=null){
            callback(res);
        }
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function get_history_list(obj,callback) {
    var qry = {
        pageSize:obj.pageSize,
        pageNo:obj.pageNo,
        orderby:obj.orderby,
        ordertype:obj.ordertype,
        token: this.token,
    };
    $.ajax({
        url: http_prefix+"/api/history/getlist",
        cache: false,
        type: "POST",
        data: JSON.stringify(qry),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function getser_key_flag(){
    return ser_key_flag;
}

function getmulti_ser_key_flag(){
    return multi_ser_key_flag;
}

function compare(pro) { 
    return function (obj1, obj2) { 
        var val1 = obj1[pro]; 
        var val2 = obj2[pro]; 
        if (val1 < val2 ) { //正序
            return 1; 
        } else if (val1 > val2 ) { 
            return -1; 
        } else { 
            return 0; 
        } 
    } 
}

async function get_detail(url){
    var ser_url = url;
    var ser_res = await geturl(ser_url);
    if(ser_res==null){
        return null;
    }else if(ser_res.id==null){
        return null;
    }else{
        return ser_res;
    }
}

async function get_mcn_detail(){
    let res = await getall_id_type_byuser();
    let content_list =await getmcn_byapi(res);
    let re_res = await save_mcn_by_id(content_list);
    return re_res;
}

async function getmcn_byapi(res) {
    let listid = res.data;
    let content_list = [];
    console.log(listid);
    for(var i=0;i<listid.length;i++){
        var tmp = listid[i];
        var id = tmp.itemid;
        var type = "";
        if(tmp.type=="answer"){
            type="0";
        }else if(tmp.type=="article"){
            type="1";
        }else{
            continue
        }
        var url = "https://www.zhihu.com/api/v4/mcn/goods/incontent?content_token="+id+"&content_type="+type+"&scenes=1";
        var ser_res = await geturl(url);

        if(ser_res.data==null || ser_res.data.length==0){
            tmp.mcn_list = [];
            content_list.push(tmp);
            continue;
        }

        var mcn_list = [];
        for(var k=0;k<ser_res.data.length;k++){
            var mcn_tmp = ser_res.data[k];
            var mcn_data={
                mcn_id:mcn_tmp.id,
                mcn_pic_url:mcn_tmp.img_url,
                mcn_name:mcn_tmp.title,
                mcn_tag:mcn_tmp.source,
                mcn_price:mcn_tmp.price_text,
                mcn_href:mcn_tmp.url,
                mcn_skuid:mcn_tmp.skuid,
                content_id:id
            }
            mcn_list.push(mcn_data);
        }
        tmp.mcn_list = mcn_list;
        content_list.push(tmp);
    }

    return content_list;
}

async function save_mcn_by_id(list){
    return new Promise(function(resolve, reject) {
        let qry ={
            token:this.token,
            list:list
        }
        $.ajax({
            url: http_prefix+"/api/content/save_mcn_by_id",
            cache: false,
            type: "POST",
            data: JSON.stringify(qry),
            contentType: "application/json",
            dataType: "json"
        }).done(function (res) {
            resolve(res);
        }).fail(function (jqXHR, textStatus) {
            reject();
        });
    })
}

async function getall_id_type_byuser(){
    return new Promise(function(resolve, reject) {
        let qry ={
            token:this.token
        }

        $.ajax({
            url: http_prefix+"/api/content/getall_id_type_byuser",
            cache: false,
            type: "POST",
            data: JSON.stringify(qry),
            contentType: "application/json",
            dataType: "json"
        }).done(function(res){
            resolve(res);
        }).fail(function (jqXHR, textStatus) {
            reject();
        });

    })
}

async function get_mcn_num(url){
    var ser_url = url;
    var ser_res = await geturl(ser_url);
    if(ser_res==null){
        return 0;
    }else{
        return ser_res.totals;
    }
}

async function answer_list(list,url){
    var ser_url = url;
    var ser_res = await geturl(ser_url);
    if(ser_res.data==null){
        return;
    }
    if(ser_res.data.length!=0){
        for(var i=0;i<ser_res.data.length;i++){
            var data = ser_res.data[i];
            if(data.type==null || data.type!="answer"){
                continue;
            }
            list.push(data.id);
            if(list.length==10){
                return;
            }
        }
    }
    if(ser_res.paging==null || ser_res.paging.is_end || ser_res.paging.next==null || ser_res.paging.next.length==0){
        return;
    }
    if(list.length<10){
        await answer_list(list,ser_res.paging.next);
    }
}

async function key_ser(list,url){
    var ser_url = url;
    var ser_res = await geturl(ser_url);
    
    if(ser_res.data==null){
        return;
    }
    if(ser_res.data.length!=0){
        for(var i=0;i<ser_res.data.length;i++){
            var data = ser_res.data[i];
            if(data.type==null || data.type!="search_result"){
                continue;
            }
            if(data.object==null || data.object.type!="answer"){
                continue;
            }
            if(data.object.question!=null){
                list.push(data.object.question.id);
                if(list.length==10){
                    return;
                }
            }
        }
    }
    
    if(ser_res.paging==null || ser_res.paging.is_end || ser_res.paging.next==null || ser_res.paging.next.length==0){
        return;
    }
    if(list.length<10){
        await key_ser(list,ser_res.paging.next);
    }
}


async function checkrp(text,callback){
    checkrp_flag = 1;
    await chrome.storage.local.remove('checkrp', function() {});
    var qry = {
        token:this.token,
        text:text
    };
    var obj = {
        text:text
    }
    // console.log(text);
    $.ajax({
        url: http_prefix+"/api/checkrepeat/check",
        cache: false,
        type: "POST",
        data: JSON.stringify(qry),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        if(res.code==0){
            obj.list = res.data;
            obj.code = res.code;
            chrome.storage.local.set({'checkrp': obj}, function() {});
        }  
        checkrp_flag = 0;
        callback(obj);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
        checkrp_flag = 0;
    });
}

async function sleep(time) {
    return new Promise(res => setTimeout(res, time))
}

function pay_info(callback) {
    $.ajax({
        url: http_prefix+"/api/login/pay_info",
        cache: false,
        type: "POST",
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function remove_his(id,callback){
    var qry = {
        token:this.token,
        id:id
    }
    $.ajax({
        url: http_prefix+"/api/history/remove",
        cache: false,
        type: "POST",
        data: JSON.stringify(qry),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        console.log(res);
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function pay_getcode(type,callback){
    var qry = {
        token:this.token,
        type:type
    }
    $.ajax({
        url: http_prefix+"/api/pay/start_pay",
        cache: false,
        type: "POST",
        data: JSON.stringify(qry),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        console.log(res);
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function check_pay_status(order_id,callback){
    var qry = {
        token:this.token,
        order_id:order_id
    }
    $.ajax({
        url: http_prefix+"/api/pay/check_pay_status",
        cache: false,
        type: "POST",
        data: JSON.stringify(qry),
        contentType: "application/json",
        dataType: "json"
    }).done(function (res) {
        console.log(res);
        callback(res);
    }).fail(function (jqXHR, textStatus) {
        // console.log(textStatus);
    });
}

function consolelog(res){
    console.log(res);
}

async function follow_q_start(id,callback){

    var stor_id = await read("follow_q");

    console.log(stor_id);
    //非会员
    // if(is_vip==0){
        if(stor_id.follow_q!=null){
            callback(0);
        }else{
            var question = {};
            var question_detail_url = "https://api.zhihu.com/questions/" + id + "?include=visit_count%2Canswer_count%2Cfollower_count";
            var detail = await get_detail(question_detail_url);
            if(detail==null || detail.id==null){
                callback(1);
            }

            if(follow_timer!=null){
                clearInterval(follow_timer);
            }

            var tmp = {};

            tmp.visit_count = detail.visit_count;
            tmp.answer_count = detail.answer_count;
            tmp.follower_count = detail.follower_count;
            tmp.date = formatDateTime(new Date());

            question.title = detail.title;
            question.url = detail.url;
            question.id= detail.id;

            question.follow_list = [tmp];

            console.log(question);

            await chrome.storage.local.set({ 'follow_q': question }, function () { });

            follow_timer = setInterval(follow_timer_init,1000*60*10);

            callback(question);
        }
    // }else{
    //     //会员
    // }
}



async function follow_timer_init(){
    var q = await read("follow_q");
    console.log("timmer***********")
    if(q.follow_q!=null){
        var id = q.follow_q.id;
        var question_detail_url = "https://api.zhihu.com/questions/" + id + "?include=visit_count%2Canswer_count%2Cfollower_count";
        var detail = await get_detail(question_detail_url);
        if(detail==null || detail.id==null){
            return;
        }

        var tmp = {};

        tmp.visit_count = detail.visit_count;
        tmp.answer_count = detail.answer_count;
        tmp.follower_count = detail.follower_count;
        tmp.date = formatDateTime(new Date());

        q.follow_q.follow_list.push(tmp);

        await chrome.storage.local.set({ 'follow_q': q.follow_q }, function () { });
    }
}